package controleBD;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import modelo.LimitesEvento;

public class UsuarioEventoDAO {

	Connection c = null;
    Statement stmt = null;
    
    public void adicionaEvento(String usuario, String evento, String min, String max){
    	try {
			Class.forName("org.sqlite.JDBC");
			c = DriverManager.getConnection("jdbc:sqlite:C:\\registro.db");
			c.setAutoCommit(false);
	    
			stmt = c.createStatement();
			min = stringFiller(min);
			max = stringFiller(max);
			String sql =	"INSERT INTO USUARIOEVENTO (USUARIO, EVENTO, MIN, MAX) " +
							"VALUES ('"+ usuario +"','"+ evento +"', '"+ min +"', '"+ max +"' )";
	    
			stmt.executeUpdate(sql);

			c.commit();
			stmt.close();
			c.commit();
			c.close();
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	  
	    
    }
    
    public void removeEvento(String usuario, String evento, String min, String max){
    	try {
			Class.forName("org.sqlite.JDBC");
			c = DriverManager.getConnection("jdbc:sqlite:C:\\registro.db");
			c.setAutoCommit(false);
	    
			stmt = c.createStatement();
			
			String sql =    "DELETE FROM USUARIOEVENTO " +
							"WHERE USUARIO='"+ usuario+"' AND EVENTO='"+ evento +"' AND MIN='"+ min +"' AND MAX='"+ max +"'";
			
			stmt.executeUpdate(sql);

			c.commit();
			stmt.close();
			c.commit();
			c.close();
    	} catch (Exception e) {
			e.printStackTrace();
		}
    	  
	    
    }

    public ArrayList<LimitesEvento> retornaEventos(String usuario){
    	
    	ArrayList<LimitesEvento> lista = new ArrayList<LimitesEvento>();
    	
    	try {
			Class.forName("org.sqlite.JDBC");
			c = DriverManager.getConnection("jdbc:sqlite:C:\\registro.db");
			c.setAutoCommit(false);
	    
			stmt = c.createStatement();
			
			ResultSet rs = stmt.executeQuery( "SELECT * FROM USUARIOEVENTO WHERE USUARIO='"+ usuario +"'");
		    while ( rs.next() ) {
		    	 
		         
		         String  evento = rs.getString("EVENTO");
		         String  min =  rs.getString("MIN");
		         String  max =  rs.getString("MAX");
		         
		         lista.add(new LimitesEvento(evento, min, max));
		         
		    }

			c.commit();
			stmt.close();
			c.commit();
			c.close();
			
			
    	} catch (Exception e) {
			e.printStackTrace();
		}
    	  
    	return lista;
    }
    public static String stringFiller(String valor){
		int intValor = Integer.parseInt(valor);
		if( intValor < 10) valor = "00".concat(valor);
		else if(intValor < 100) valor = "0".concat(valor);
		return valor;
	}
}
